package ucl.cs.bank.server;

/**
 * UCLBank Implementation.
 * @author  K. Bryson.
 * @version 1.0
 */
///////////////// WHY DOES THIS NOT WORK CORRECTLY ? //////////////////
import java.rmi.RemoteException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import ucl.cs.bank.common.*;

public class UCLBankImpl implements UCLBank {

   private Map<Integer, UCLAccount> accounts =
                                  new ConcurrentHashMap<Integer, UCLAccount>();

   static final long serialVersionUID = 1;
   private static int next_account_number = 0;

   public UCLBankImpl() throws java.rmi.RemoteException { super();} 

   public synchronized int createAccount(String name) throws RemoteException {
    
      int account_number = next_account_number;
      threadRest();
      next_account_number++;

      System.out.println("Creating account number " + account_number);
      UCLAccount account = new UCLAccountImpl(name, account_number);

      accounts.put(account_number, account);

      return account_number;
   }

   public void deleteAccount(int account_number) throws RemoteException, NoSuchAccountException {

      if (! accounts.containsKey(account_number)) {
         throw new NoSuchAccountException("Account number " + account_number + " does not exist.");
      }

      accounts.remove(account_number);
   }

   public synchronized UCLAccount getAccount(int account_number) throws RemoteException, NoSuchAccountException {

      if (! accounts.containsKey(account_number)) {
         throw new NoSuchAccountException("Account number " + account_number + " does not exist.");
      }

      return (UCLAccount)accounts.get(account_number);
   }
   

   public UCLAccountInfo[] listAccounts() throws RemoteException {
	 
      UCLAccountInfo[] info_array = new UCLAccountInfo[accounts.size()];

      Iterator<UCLAccount> iter = accounts.values().iterator();
     
      int index = 0;
      while (iter.hasNext()) {
         UCLAccount account = iter.next();
         info_array[index++] = new UCLAccountInfo(account.getName(), account.getNumber(), account.getBalance());
      }

      return info_array;
   }
      
   private void threadRest() {
      try {
         Thread.sleep(10000);
      }
      catch (InterruptedException except) {
      }
   }
}
